<template>
  <basic-container>
    <avue-crud :option="option" :data="data" ref="crud" v-model="form" :permission="permissionList" @row-del="rowDel"
      @row-update="rowUpdate" @row-save="rowSave" :before-open="beforeOpen" :page="page" @search-change="searchChange"
      @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @on-load="onLoad" @keydown.native="keydown($event)">
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.user_delete" @click="handleDelete">删
          除
        </el-button>
        <el-button type="primary" size="small" plain v-if="permission.user_reset" icon="el-icon-refresh" @click="handleReset">密码重置
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="roleId">
        <el-tag>{{row.roleName}}</el-tag>
      </template>
      <template slot-scope="{row}" slot="deptId">
        <el-tag>{{row.deptName}}</el-tag>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {
    getList,
    getUser,
    remove,
    update,
    add,
    resetPassword
  } from "@/api/system/user";
  // import {
  //   getDeptTree
  // } from "@/api/system/dept";
  import {
    getDeptCityTree
  } from "@/api/system/dept";
  import {
    getRoleTree
  } from "@/api/system/role";
  import {
    mapGetters
  } from "vuex";
  // import website from '@/config/website';

  export default {
    data() {
      const validatePass = (rule, value, callback) => {
        this.form.password = value.replace(/\s+/g, '');
        if (value === '' || value === undefined) {
          callback(new Error('请输入新密码'));
        } else if(value.length < 8 || value.length > 16) {
          callback(new Error('新密码长度为8~16'));
        } else if((/[0-9]/).test(value) && (/[a-zA-Z]/).test(value)) {
          callback();
        } else {
          callback(new Error('新密码必须含有数字和英文'));
        }
      };
      const validatePass2 = (rule, value, callback) => {
        this.form.password2 = value.replace(/\s+/g, '')
        if (value === '' || value === undefined) {
          callback(new Error('请再次输入密码'));
        } else if(value !== this.form.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      const validatePass3 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('登录账号不能为空'));
        } else {
          this.form.account = value.replace(/[^a-zA-Z\u4e00-\u9fa5]/g, '');
          callback();
        }
      };
      // const validatePass4 = (rule, value, callback) => {
      //   if (value === '') {
      //     callback(new Error('用户昵称不能为空'));
      //   } else {
      //     this.form.name = value.replace(/\s+/g, '');
      //     callback();
      //   }
      // };
      // const validatePass5 = (rule, value, callback) => {
      //   if (value === '') {
      //     callback(new Error('用户姓名不能为空'));
      //   } else {
      //     this.form.realName = value.replace(/\s+/g, '');
      //     callback();
      //   }
      // };
      const validatePass6 = (rule, value, callback) => {
        let regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (value !== '' && !regEmail.test(value)) {
          callback(new Error('电子邮箱格式不正确'));
        } else {
          callback();
        }
      };
      const validatePass7 = (rule, value, callback) => {
        let regEmail = /^[1]+[0-9]{10}$/
        if (value == '') {
          callback(new Error('手机号码不能为空'));
        } else if (value !== '' && !regEmail.test(value)) {
          callback(new Error('手机号码格式不正确'));
        } else if (value !== '' && value.length > 11) {
          callback(new Error('手机号码格式不正确'));
        } else {
          callback();
        }
      };
      return {
        form: {
          deptId: 1,
          roleName: '11'
        },
        selectionList: [],
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        init: {
          roleTree: [],
          deptTree: [],
        },
        option: {
          tip: false,
          border: true,
          index: true,
          columnBtn: false, // 列显隐按钮
          refreshBtn: false, // 刷新按钮
          searchBtn: false, // 搜索显隐按钮（当 column 中有搜索的属性，或则 searchsolt 为 true 时自定义搜索启动起作用）
          selection: true,
          viewBtn: true,
          dialogHeight: 450,
          column: [{
              label: "登录账号",
              prop: "account",
              search: true,
              rules: [{
                required: true,
                validator: validatePass3,
                trigger: 'change'
              }],
              // span: website.tenantMode ? 12 : 24,
            },
            // 隐藏
            // {
            //   label: "所属租户",
            //   prop: "tenantId",
            //   type: "tree",
            //   dicUrl: "/api/xmbz-system/tenant/select",
            //   props: {
            //     label: "tenantName",
            //     value: "tenantId"
            //   },
            //   hide: !website.tenantMode,
            //   addDisplay: website.tenantMode,
            //   editDisplay: website.tenantMode,
            //   viewDisplay: website.tenantMode,
            //   search: website.tenantMode,
            //   rules: [{
            //     required: true,
            //     message: "请输入所属租户",
            //     trigger: "click"
            //   }]
            // },
            {
              label: '密码',
              prop: 'password',
              hide: true,
              editDisplay: false,
              viewDisplay: false,
              rules: [{
                required: true,
                validator: validatePass,
                trigger: 'change'
              }]
            },
            {
              label: '确认密码',
              prop: 'password2',
              hide: true,
              editDisplay: false,
              viewDisplay: false,
              rules: [{
                required: true,
                validator: validatePass2,
                trigger: 'change'
              }]
            },
            // 隐藏
            // {
            //   label: "用户昵称",
            //   prop: "name",
            //   search: true,
            //   rules: [{
            //     required: true,
            //     validator: validatePass4,
            //     trigger: "change"
            //   }]
            // },
            // {
            //   label: "用户姓名",
            //   prop: "realName",
            //   rules: [{
            //     required: true,
            //     validator: validatePass5,
            //     trigger: "change"
            //   }]
            // },
            {
              label: "所属角色",
              prop: "roleId",
              multiple: true,
              checkStrictly: true,
              defaultExpandAll: true,// 默认展开所有节点
              checked: this.getroldList,
              type: "tree",
              dicData: [],
              props: {
                label: "title",
                // value: "id"
              },
              slot: true,
              rules: [{
                required: true,
                // message: "请选择所属角色",
                validator: (rule, value, callback)=>{
                  if(String(value) == '0') value = [];// 操作不规范(例如打开任一用户的编辑，点击弹窗关闭后，再打开新建)导致所属角色数组有ID 0
                  this.roleIdCopy = value;
                  // console.log('value',value,value.length,);
                  if (value === '' || value.length == 0) {
                    callback(new Error('请选择所属角色'));
                  } else {
                    callback();
                  }
                },
                trigger: "change"
              }]
            },
            // {
            //   label: "所属部门",
            //   prop: "deptId",
            //   type: "tree",
            //   hide: true,
            //   dicData: [],
            //   props: {
            //     label: "deptName"
            //   },
            //   slot: true,
            //   rules: [{
            //     required: true,
            //     message: "请选择所属部门",
            //     trigger: "click"
            //   }]
            // },
            {
              label: "所属城市",
              prop: 'deptId',
              dicData: {},
              type: "tree",
              props: {
                label: "deptName",
                value: 'id',
              },
              slot: true,
              rules: [{
                required: true,
                // message: "请选择所属部门",
                validator: (rule, value, callback)=>{
                  if(String(value) == '0') this.form.deptId = value = '';// 操作不规范(例如打开任一用户的编辑，点击弹窗关闭后，再打开新建)导致所属角色数组有ID 0
                  if (value === '') {
                    callback(new Error('请选择所属部门'));
                  } else {
                    callback();
                  }
                },
                trigger: "change"
              }]
            },
            {
              label: "手机号码",
              prop: "phone",
              overHidden: true,
              maxlength: 11,
              rules: [{
                required: true,
                validator: validatePass7,
                trigger: "change"
              }]
            },
            {
              label: "电子邮箱",
              prop: "email",
              hide: true,
              overHidden: true,
              rules: [{
                required: false,
                validator: validatePass6,
                trigger: "change"
              }]
            },
            {
              label: "用户性别",
              prop: "sex",
              type: "select",
              dicData: [{
                  label: "男",
                  value: 1
                },
                {
                  label: "女",
                  value: 2
                },
                {
                  label: "未知",
                  value: 3
                }
              ],
              hide: true,
              rules: [{
                required: true,
                message: '请填写用户性别',
                trigger: "blur"
              }]
            },
            {
              label: "用户生日",
              type: "date",
              prop: "birthday",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              hide: true
            },
            {
              label: "账号状态",
              prop: "statusName",
              hide: true,
              display: false
            }
          ]
        },
        data: [],
        roleIdCopy: [],
      };
    },
    created() {
      window.addEventListener("keydown",this.keyupEnter);
    },
    watch: {
      'form.tenantId'() {
        if (this.form.tenantId !== '') {
          // getDeptTree(this.form.tenantId).then(res => {
          //   console.log('getDeptTree',res.data.data)
          //   const index = this.$refs.crud.findColumnIndex("deptId");
          //   this.option.column[index].dicData = res.data.data;
          // });
          // console.log('00000')
          getDeptCityTree().then(res => {
            const data = res.data.data;
            const index = this.$refs.crud.findColumnIndex("deptId");
            this.option.column[index].dicData = data;
          });
          getRoleTree(this.form.tenantId).then(res => {
            const index = this.$refs.crud.findColumnIndex("roleId");
            this.option.column[index].dicData = res.data.data;
          });
          setTimeout(() => {
            let deptNameArray = [];
            this.form.deptId = Number(this.form.deptId);
            this.form.roleId = `${this.form.roleId}`;
            this.form.roleId = this.form.roleId.split(",");
            this.form.roleId.forEach((item,index) => {
              this.form.roleId[index] = Number(item);
            })
            this.form.roleName = `${this.form.roleName}`;
            this.form.roleName = this.form.roleName.split(",");
          },500)
        }
      },
      'roleIdCopy'() {
        if(this.roleIdCopy !== undefined) {
          this.getroleIdList(this.roleIdList);
          this.form.roleId = this.roleIdCopy;
        }
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.user_add, false),
          viewBtn: this.vaildData(this.permission.user_view, false),
          delBtn: this.vaildData(this.permission.user_delete, false),
          editBtn: this.vaildData(this.permission.user_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
    },
    methods: {
      rowSave(row, loading, done) {
        row.roleId = row.roleId.join(",");
        row.tenantId = "000000"
        row.$tenantId = "管理组"
        row.name = row.account
        row.realName = row.account
        // console.log(row,this.form)
        if(row.deptId == 1 || row.deptId == 0) {
          // console.log('')
          this.$message({
            type: "warning",
            message: "上级部门无法选择全国!"
          });
          this.onLoad(this.page);
          done();
        } else {
          add(row).then(() => {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, error => {
            done();
            console.log(error);
          });
        }
      },
      rowUpdate(row, index, loading, done) {
        // console.log('修改',row)
        row.roleId = row.roleId.join(",");
        row.tenantId = "000000"
        row.$tenantId = "管理组"
        row.name = row.account
        row.realName = row.account
        // console.log(row,'this.form',this.form.roleId)
        if(row.deptId == 1 || row.deptId == 0) {
          // console.log('')
          this.$message({
            type: "warning",
            message: "上级部门无法选择全国!"
          });
          this.onLoad(this.page);
          done();
        } else {
          update(row).then(() => {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, error => {
            done();
            console.log(error);
          });
        }
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      searchReset() { 
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params) {
        this.page.currentPage = 1;
        let cityId = JSON.parse(window.localStorage.getItem("saber-areaId")).content
        params.deptId = cityId;
        this.query = params;
        this.onLoad(this.page, params);
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleReset() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择账号密码重置为 Xm5201314 吗?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            return resetPassword(this.ids);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this.getroleId = '';
        // console.log('打开',this.getroleId)
        if (["edit", "view"].includes(type)) {
          getUser(this.form.id).then(res => {
            console.log(this.form, 'orr')
            this.form.deptId = res.data.data.deptName
            this.form.deptId = res.data.data.deptId
            this.form.roleName = res.data.data.roleName
            // console.log(res.data.data.deptId[0],'this.form.deptId',res.data.data.deptId)
            this.form = res.data.data;
            this.form.deptId = this.form.deptId.split(",");
            this.form.deptId.forEach((ele, index) => {
              // console.log(Number(ele),'999')
              this.form.deptId[index] = Number(ele);
            });
            // console.log('this.form',this.form,res.data.data)
            this.form.roleId = this.form.roleId.split(",");
            this.form.roleId.forEach((ele, index) => {
              this.form.roleId[index] = Number(ele);
            });
            // this.form.roleId = this.form.roleId.split(",");
            // this.form.roleId.forEach((ele, index) => {
            //   this.form.roleId[index] = Number(ele);
            // });
          });
        }
        done();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        let cityId = JSON.parse(window.localStorage.getItem("saber-areaId")).content
        params.deptId = cityId
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          // console.log('data',data)
        });
        // getDeptCityTree(this.form.tenantId).then(res => {
        //   console.log('res.data.data',res.data.data)
        //   const index = this.$refs.crud.findColumnIndex("deptId");
        //   console.log(this.$refs.crud.findColumnIndex("deptId"),'this.$refs.crud.findColumnIndex("deptId");')
        //   this.option.column[index].dicData = res.data.data;
        // });
        getDeptCityTree(this.form.tenantId).then(res => {
          const data = res.data.data;
          const index = this.$refs.crud.findColumnIndex("deptId");
          // console.log(index,'index',this.option.column[index].dicData,'this.option.column[index].dicData')
          this.option.column[index].dicData = data;
          // console.log(this.option,'this.option')
        });
        getRoleTree(this.form.tenantId).then(res => {
          const index = this.$refs.crud.findColumnIndex("roleId");
          this.option.column[index].dicData = res.data.data;
          this.roleIdList = res.data.data;
        });
      },
      // 禁止输入空格
      keydown(event){
        if(event.keyCode == 32){
          event.returnValue = false
        }
      },
      // 回车事件
      keyupEnter(){
        let dialogArray = document.getElementsByClassName('avue-crud__dialog');
        let displayArray = [];
        for(let i = 0;i < dialogArray.length;i++) {
          if(dialogArray[i].style.display == '') displayArray.push(false);
        }
        if(displayArray.indexOf(false) == -1) {
          if(window.event.keyCode == 13 ){
            let inputArrays = document.getElementsByClassName('el-input__inner');
            let account = '';
            for(let i = 0;i < inputArrays.length;i++) {
              console.log(inputArrays[i].placeholder)
              if(inputArrays[i].placeholder == '登录账号') account = inputArrays[i].value
            }
            this.query.account = account;
            this.onLoad(this.page, this.query);
            event.returnValue = false;
          }
        }
      },
      getroldList(data) {
        this.getroleId = data.id;
        // this.getroleIdList(this.roleIdList);
      },
      getroleIdList(roleIdList) {
        if((this.form.roleId.indexOf(this.getroleId) > -1) && (this.getroleId !== '')) {
          this.roleIddisabledFlag = true;
        } else {
          this.roleIddisabledFlag = false;
        }
        roleIdList.forEach((item,index) => {
          if(item.children !== undefined) {
            this.getroleIdList(item.children);
            if(item.id == this.getroleId || item.parentId == this.getroleId) {
              item.children.forEach(childitem => {
                if(this.form.roleId.indexOf(this.getroleId) > -1) {
                  childitem.disabled = this.roleIddisabledFlag;
                  if(childitem.disabled) this.delRoleId(childitem.id)
                  this.isChild(childitem,childitem.disabled)
                } else {
                  childitem.disabled = this.roleIddisabledFlag;
                  if(childitem.disabled) this.delRoleId(childitem.id)
                  this.isChild(childitem,childitem.disabled);
                }
              })
            }
          }
        })
        const index = this.$refs.crud.findColumnIndex("roleId");
        this.option.column[index].dicData = roleIdList;
      },
      isChild(item,disabled) {
        if(item.children !== undefined) {
          let childitems = item.children;
          childitems.forEach(childchild => {
            childchild.disabled = disabled;
            if(childchild.disabled) this.delRoleId(childchild.id);
            this.isChild(childchild,disabled);
          })
        }
      },
      delRoleId(id) {
        const fileFind = id;
        const findThisNum = this.form.roleId.findIndex(x => x === fileFind );
        if(findThisNum >= 0) this.form.roleId = this.form.roleId.splice(findThisNum, 1);
      }
    },
    destroyed() {
      window.removeEventListener("keydown",this.keyupEnter);
    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated() {
      window.addEventListener("keydown",this.keyupEnter);
    },
    deactivated() {
      window.removeEventListener("keydown",this.keyupEnter);
    }
  };
</script>

<style>
</style>
